<template>
  <div class="map-content">
    <div ref="mapChart" style="width: 100%; height: 50vh"></div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import fujianJSON from '@/assets/json/fujian.json'
import sanmingJson from '@/assets/json/sanming.json'
import nanpingJson from '@/assets/json/nanping.json'
import ningdeJson from '@/assets/json/ningde.json'
import fuzhouJson from '@/assets/json/fuzhou.json'
import putianJson from '@/assets/json/putian.json'
import quanzhouJson from '@/assets/json/quanzhou.json'
import xiamenJson from '@/assets/json/xiamen.json'
import zhangzhouJson from '@/assets/json/zhangzhou.json'
import longyanJson from '@/assets/json/longyan.json'
import * as echarts from 'echarts'
import { watch } from 'vue'

// ref or data
const mapChart = ref()
const options = ref()
let myMapChart: any = ref()
const zoom = 0.8
const mTime = ref()
let dt: any = ref([
  {
    name: '南平市',
    unitId: '10350701'
  },
  {
    name: '宁德市',
    unitId: '10350901'
  },
  {
    name: '三明市',
    unitId: '10350401'
  },
  {
    name: '福州市',
    unitId: '10350101'
  },
  {
    name: '莆田市',
    unitId: '10350301'
  },
  {
    name: '泉州市',
    unitId: '10350501'
  },
  {
    name: '龙岩市',
    unitId: '10350801'
  },
  {
    name: '漳州市',
    unitId: '10350601'
  },
  {
    name: '厦门市',
    unitId: '10350201'
  }
])

// 标记点数据
let _data: any = ref([
  {
    name: '武夷烟叶',
    value: [117.495646, 27.294385],
    count: 0
  },
  {
    name: '三明金叶复烤',
    value: [117.555184, 26.179113],
    count: 0
  },
  {
    name: '海晟投资',
    value: [118.112537, 24.477882],
    count: 0
  },
  {
    name: '福建进出口',
    value: [118.104901, 24.473043],
    count: 0
  }
])

// emits
const emits = defineEmits({
  CMapChartClick: (data) => !!data,
  setMapUnitId: (data) => !!data
})

const props = defineProps({
  allAreaData: {
    type: Object,
    default: () => {}
  }
})

watch(
  () => props.allAreaData,
  (newVal: any) => {
    // console.log(newVal, 'watch')
    if (newVal && newVal.area && newVal.area.length) {
      // dt.value = newVal.area
      newVal.area.forEach((item: any) => {
        dt.value.forEach((v: any) => {
          if (Number(v.unitId) === Number(item.unitId)) v.value = item.score
        })
      })
    }
    initOptions()
  },
  {
    deep: true
  }
)

onMounted(() => {
  // if (mTime.value) clearInterval(mTime.value)
  // initOptions()
})

// mwthod
const initOptions = () => {
  echarts.registerMap('fujianJSON', fujianJSON as any)
  myMapChart.value = echarts.init(mapChart.value)

  // 判断 地图显示那个颜色的数据源

  var series: any = []

  series.push(
    {
      type: 'map',
      map: 'fujianJSON',
      zlevel: 0,
      zoom: zoom,
      // 地图是否开启鼠标滚动缩放或拖拽
      // roam: true,
      // silent: true, //禁用地图的hover事件
      itemStyle: {
        normal: {
          // borderColor: 'transparent',
          color: '#333',
          // 地图默认背景颜色
          areaColor: '#409eff',
          borderColor: '#fff',
          borderWidth: 0.2
        },
        // 鼠标移动地图时的背景颜色
        emphasis: {
          areaColor: '#4B7902',
          label: {
            show: true,
            textStyle: {
              color: '#fff' //鼠标经过字体颜色
            }
          }
        }
      },
      label: {
        normal: {
          show: true,
          textStyle: {
            color: '#333'
          }
        }
      },
      layoutCenter: ['45%', '50%'],
      layoutSize: '120%',
      data: dt.value,
      selectedMode: false // 去除地图点击后的黄色背景颜色
    },
    {
      type: 'effectScatter',
      coordinateSystem: 'geo',
      z: 3,
      zlevel: 99,
      symbolSize: 10,
      rippleEffect: {
        // 坐标点动画
        period: 2,
        scale: 4,
        brushType: 'fill'
      },
      label: {
        // 自定义 标记点的 字体描述 样式
        normal: {
          show: true,
          position: 'top',
          formatter: '  {b}',
          color: '#333',
          fontWeight: 'bold',
          fontSize: 12
        }
      },
      data: _data,
      itemStyle: {
        // 坐标点颜色
        normal: {
          color: function (params: any) {
            // console.log(params)
            const data = params.data
            let color = ''
            if (data.count > 630) {
              color = 'rgba(133, 185, 98, 1)'
            }
            if (data.count >= 560 && data.count <= 629) {
              color = 'rgba(255, 255, 38, 1)'
            }
            if (data.count >= 420 && data.count <= 559) {
              color = 'rgba(255, 201, 38, 1)'
            }
            if (data.count <= 420) {
              color = 'rgba(255, 38, 38, 1)'
            }
            return color
          }
        }
      }
    }
  )

  options.value = {
    // tooltip: {
    //   show: true, //是否显示提示框组件，包括提示框浮层和 axisPointer。
    //   trigger: 'item', //触发类型。item,axis,none
    //   enterable: true, //鼠标是否可进入提示框浮层中，默认为false，
    //   showContent: true, //是否显示提示框浮层
    //   triggerOn: 'mousemove', //提示框触发的条件(mousemove|click|none)
    //   showDelay: 0, //浮层显示的延迟，单位为 ms，默认没有延迟，也不建议设置。在 triggerOn 为 'mousemove' 时有效。
    //   textStyle: {
    //     color: '#FFF',
    //     fontSize: 12
    //   },
    //   padding: [6, 10],
    //   hideDelay: 10, //浮层隐藏的延迟
    //   // <p style="color: #333">${o.data.count}</p>
    //   formatter: (o: any) =>
    //     o.data
    //       ? `<section class="map-hover-box"><div class="map-hover-mov">
    //                     <h3 style="color: #333">${o.name}</h3>
    //                     </div><i></i>
    //                     </section>`
    //       : '',
    //   alwaysShowContent: true,
    //   // 防止 tootip 偏移严重
    //   // position: 'inside',
    //   transitionDuration: 1 //提示框浮层的移动动画过渡时间，单位是 s，设置为 0 的时候会紧跟着鼠标移动。
    // },
    visualMap: {
      //视觉映射组件
      // type: 'piecewise', //分段型。
      // splitNumber: 6,
      // inverse: true,
      pieces: [
        {
          min: 630,
          label: '好(630分以上)',
          color: '#85b962'
        },
        {
          min: 420,
          max: 559,
          label: '一般(420分~559分)',
          color: '#ffc926'
        },
        {
          min: 560,
          max: 629,
          label: '较好(560分~629分)',
          color: '#ffff26'
        },
        {
          max: 420,
          label: '差(420分以下)',
          color: '#ff2626'
        }
      ],
      left: 'right',
      bottom: '0%',
      textStyle: {
        color: '#333'
      }
    },
    geo: {
      map: 'fujianJSON',
      // 地图缩放
      zoom: zoom,
      // roam: true,
      layoutCenter: ['45%', '50%'],
      layoutSize: '120%',
      itemStyle: {
        normal: {
          borderColor: '#c0f3fb',
          borderWidth: 1,
          shadowColor: '#8cd3ef',
          shadowOffsetY: 10,
          shadowBlur: 100
          //   // 地图默认背景颜色
          // areaColor: '#00BCFF'
        }
      }
    },
    series: series
  }

  if (options.value && typeof options.value === 'object') {
    myMapChart.value.setOption(options.value)
  }
  // 地图点击事件
  myMapChart.value.on('click', (e: any) => {
    console.log(e, 'e---')
    if (
      e.name === '武夷烟叶' ||
      e.name === '三明金叶复烤' ||
      e.name === '海晟投资' ||
      e.name === '福建进出口'
    )
      return
    let newMapJson = {}
    // 最笨的方法
    if (e.name === '三明市') newMapJson = sanmingJson
    else if (e.name === '南平市') newMapJson = nanpingJson
    else if (e.name === '宁德市') newMapJson = ningdeJson
    else if (e.name === '福州市') newMapJson = fuzhouJson
    else if (e.name === '莆田市') newMapJson = putianJson
    else if (e.name === '泉州市') newMapJson = quanzhouJson
    else if (e.name === '厦门市') newMapJson = xiamenJson
    else if (e.name === '漳州市') newMapJson = zhangzhouJson
    else newMapJson = longyanJson
    const data = {
      showCMap: false,
      mapData: e.data,
      newMapData: newMapJson
    }
    emits('CMapChartClick', data)
    emits('setMapUnitId', e.data?.unitId)
  })
  // window.addEventListener('resize', resize)

  // setIntervalHandler()

  // 鼠标移入， 停止滚动
  // myMapChart.value.on('mousemove', () => {
  //   clearInterval(mTime.value)
  // })
  // // 鼠标移出来，自动滚动
  // myMapChart.value.on('mouseout', () => {
  //   clearInterval(mTime.value)
  //   setIntervalHandler()
  // })
}

const setIntervalHandler = () => {
  let index = 0 //播放所在下标
  mTime.value = setInterval(function () {
    myMapChart.value.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: index
    })
    index++
    if (index >= options.value.series[0].data.length) {
      index = 0
    }
  }, 3000)
}

const resize = () => {
  setTimeout(() => {
    if (myMapChart.value) {
      myMapChart.value.resize()
    }
  }, 50)
}

defineOptions({
  name: 'CMap'
})
</script>

<style scoped lang="scss">
.map-content {
  display: flex;
  align-items: flex-end;
  .moddle_box {
    width: 200px;
    .middle-div {
      display: flex;
      align-items: center;
      padding-top: 4px;
      padding-bottom: 4px;
      font-size: 12px;
      .middle-span {
        width: 10px;
        height: 10px;
        margin-right: 10px;
      }
      .item1 {
        background-color: #85b962;
      }

      .item2 {
        background-color: #ffff26;
      }

      .item3 {
        background-color: #ffc926;
      }

      .item4 {
        background-color: #ff2626;
      }
    }
  }
}
</style>
